package com.mybdqn.shiro.realm;

import com.mybdqn.pojo.Permission;
import com.mybdqn.pojo.Role;
import com.mybdqn.pojo.User;
import com.mybdqn.service.PermissionService;
import com.mybdqn.service.RoleService;
import com.mybdqn.service.UserService;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * Created by chenliheng on 2017/12/14.
 */
@Component
public class CustomRealm extends AuthorizingRealm {

    @Autowired
    private UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;

    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    /**
     * 权限验证方法
     * @param principalCollection
     * @return
     */
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {

        // 获取用户身份
        String userCode = (String) principalCollection.getPrimaryPrincipal();
        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        try {
            // 查询用户角色
            Set<String> roleNames = roleService.getRoleByUserCode(userCode);
            info.setRoles(roleNames);
            // 查询用户权限
            Set<String> permissionNames = permissionService.getPermissionByRoleNames(roleNames);
            info.setStringPermissions(permissionNames);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return info;
    }

    /**
     * 身份验证方法
     * @param authenticationToken
     * @return
     * @throws AuthenticationException
     */
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) {
        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        Map<String,Object> param = new HashMap<String,Object>();
        param.put("userCode", token.getUsername());
        //param.put("password", token.getPassword());
        try {
            List<User> list = userService.getUserListByMap(param);
            if(list.size() == 0){
                throw new UnknownAccountException();
            }
            User user = list.get(0);
            return new SimpleAuthenticationInfo(user.getUserCode(), user.getPassword(), getName());

        } catch (Exception e) {
            e.printStackTrace();
        }

        throw new AuthenticationException();
    }
}
